

package com.hazelcast.test.starter.constructor;

import com.hazelcast.test.starter.HazelcastStarterConstructor;

import java.lang.reflect.Constructor;
import java.util.UUID;

import static com.hazelcast.test.starter.HazelcastProxyFactory.proxyArgumentsIfNeeded;
import static com.hazelcast.test.starter.ReflectionUtils.getFieldValueReflectively;

@HazelcastStarterConstructor(classNames = {"com.hazelcast.internal.partition.PartitionReplica"})
public class PartitionReplicaConstructor extends AbstractStarterObjectConstructor {

    public PartitionReplicaConstructor(Class<?> targetClass) {
        super(targetClass);
    }

    @Override
    Object createNew0(Object delegate) throws Exception {
        ClassLoader classloader = targetClass.getClassLoader();
        Class<?> replicaClass = classloader.loadClass("com.hazelcast.internal.partition.PartitionReplica");
        Class<?> addressClass = classloader.loadClass("com.hazelcast.cluster.Address");
        Constructor<?> constructor = targetClass.getDeclaredConstructor(addressClass, UUID.class);

        Object address = getFieldValueReflectively(delegate, "address");
        Object uuid = getFieldValueReflectively(delegate, "uuid");

        Object[] args = new Object[]{address, uuid};
        Object[] proxiedArgs = proxyArgumentsIfNeeded(args, classloader);

        return constructor.newInstance(proxiedArgs);
    }
}
